package com.ethanzzh.ethanzzh_xdclass.service;

import com.ethanzzh.ethanzzh_xdclass.config.WeChatConfig;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.util.Random;

@Service
public class SmsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsService.class);

    @Autowired
    private WeChatConfig weChatConfig;

    public String sendSMS(String phoneNum) {

        String smsCode = String.valueOf(new Random().nextInt(999999));//随机生成验证码

        String[] params = {smsCode, "5"};//参数，验证码为smsCode，100秒内填写
        String sign = "ethanzzh"; //这个是签名内容  在申请的时候填的

        try {
            SmsSingleSender smsSingleSender = new SmsSingleSender(weChatConfig.getSmsAppid(), weChatConfig.getSmsKey());
            SmsSingleSenderResult result = smsSingleSender.sendWithParam("86",
                    phoneNum, weChatConfig.getTpl_id(), params,sign,"","");
            LOGGER.info("result: " + result.toString());


            return result.errMsg;


        } catch (HTTPException e) {
            // HTTP响应码错误
            e.printStackTrace();

        } catch (JSONException e) {
            // json解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            e.printStackTrace();
        } catch (Exception e) {
            // 网络IO错误
            e.printStackTrace();


        }
        return null;
    }
}
